/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.tang.tframe.sdm.web.taglib;

import cn.tang.tframe.common.utils.lang.StringUtils;
import org.springframework.web.servlet.support.JspAwareRequestContext;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.tags.RequestContextAwareTag;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

/**
 * @author tanghc
 */
public class ActiveMenuClassTagHandler extends SimpleTagSupport {

	private String uriKey;

	private RequestContext requestContext;
	private PageContext pageContext;
	/**
	 * Called by the container to invoke this tag. The implementation of this
	 * method is provided by the tag library developer, and handles all tag
	 * processing, body iteration, etc.
	 */
	@Override
	public void doTag() throws JspException {
		init();
		// Get JSP Context
		if(null != pageContext){
			HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
			String uri = null == this.requestContext?(String)request.getAttribute("javax.servlet.forward.request_uri"):this.requestContext.getRequestUri();
			if(StringUtils.isNotBlank(uri)){
				uri = uri.replaceFirst(request.getContextPath() , "");
			} else {request.getRequestURL();
				uri = "";
			}
			if (StringUtils.isNoneBlank(uriKey) && uri.startsWith("/" +uriKey)) {
				write(pageContext.getOut(), " active");
				return;
			}
		}
	}

	public String getUriKey() {
		return uriKey;
	}

	public void setUriKey(String uriKey) {
		this.uriKey = uriKey;
	}

	private void write(JspWriter out, String classes) {
		try {
			out.print(classes);
		} catch (IOException ex) {
		}
	}
	public void init(){
		if(null == pageContext || null == requestContext){
			JspContext jspContext = getJspContext();
			if (jspContext instanceof PageContext) {
				this.pageContext = (PageContext) jspContext;
				this.requestContext = (RequestContext) pageContext.getAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE);
				if (this.requestContext == null) {
					this.requestContext = new JspAwareRequestContext(pageContext);
					pageContext.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, this.requestContext);
				}
			}
		}
	}
}
